import {defineStore, storeToRefs} from 'pinia';
import {umsMemberApi as api} from '/@/api/ums/member/index';
import {ElMessage} from "element-plus";

// 客户阶段
import {stageStatusCache} from "/@/stores/ums/customer/stageStatusStores";
const { list:stageList } = storeToRefs(stageStatusCache());

// 客户类型
import {customerTypeCache } from "/@/stores/ums/customer/typeStores";
const { list:customerTypeList } = storeToRefs(customerTypeCache());

// 客户来源
import { sourceCache } from "/@/stores/ums/customer/sourceStores";
const { list:sourceList } = storeToRefs(sourceCache());

// 产品线
import { productLineCache } from "/@/stores/ums/customer/productLineStores";
const { list:productLineList } = storeToRefs(productLineCache());


/**
 * 客户列表
 */
export default defineStore('customerListStore', {
	state: ():any => ({
		lock: false,// Get 加载的锁
		title: '客户列表',// 标题
		pageList:[],// 分页列表
		pageTotal: 0,// 记录数
		pageSize: 10,// 页容
		pageCurrent: 1,// 当前页
		pageLoading: false,// 加载显示移除控制
		page:{
			records: [],// 分页数据
			total: 0,// 记录数
			size: 10,//
			current: 1,//
		},
	}),

	getters: {

		/**
		 * <p>获取客户列表</p>
		 * 使用全局缓存组装数据解决多次访问端压力
		 * @author starshine 小郭
		 */
		opportunityList:state => {
			return state.pageList.map((l: any) => {

				// 回填客户阶段
				l['stageName'] = stageList.value.filter((f: any) => l['stageId'] === f['id'])[0]?.name
				// 回填客户类型
				l['type'] = customerTypeList.value.filter((f: any) => l['customerType'] === f['id'])[0]?.name
				// 回填客户来源渠道
				l['source'] = sourceList.value.filter((f: any) => l['sourceChannel'] === f['id'])[0]?.name
				// 客户来源场景
				l['scene'] = sourceList.value.filter((f: any) => l['sourceScene'] === f['id'])[0]?.name
				// 产品线
				l['productLineName'] = productLineList.value.filter((f: any) => l['productLineId'] === f['id'])[0]?.name
				// 修改合作该率
				if (l['probability']) l['probability'] = l['probability'] + '%'

				return l
			})
		}

	},

	actions: {

		/** 加载 */
		async loadList(params: any):Promise<void> {
			this.pageLoading = true
			try{
				const {data} = await api().query(params);
				this.pageList = data.records
				this.pageTotal = data.total
				this.pageSize = data.size
				this.pageCurrent = data.current
			}catch (e:any){
				console.log('获取'+this.title+'列表异常捕获\n',e);
				ElMessage.error(e.message)
			}
			this.lock = false
			this.pageLoading = false
		},

		restPage(){
			this.pageList = [];
			this.pageTotal = 0;
			this.pageSize = 20;
			this.pageCurrent = 1;
		}

	},
});



